import SocketServer
import cPickle
from dataclasses import deviceSystem

class BackendServerBase(object):
    def __init__(self, address, port):
        self.DeviceSystem = deviceSystem()
        self.models = {}
        self.models.update({'DeviceSystem':self.DeviceSystem})
        self.address = address
        self.port = port
        self.Server = BackendSocketServer(self.DeviceSystem, address, port)
        self.start_server()
    def start_server(self):
        self.Server.serve_forever()
    

class BackendSocketServer(SocketServer.TCPServer):
    def __init__(self, DeviceSystem, address, port):
        SocketServer.TCPServer.__init__(self, (address, port), BackendSocketReqHandler)
        #self.models = models
        self.DeviceSystem = DeviceSystem

class BackendSocketReqHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        buffer = self.rfile.readline()
        print 'buffer=', buffer
        cmd = buffer.strip()
        #cmd = buffer[0].strip()
        print 'cmd=', cmd
#        buffer.remove(0)
#        data = str()
#        for line in buffer:
#            data = data + line
#        print 'data=', data
        self.parse_cmd(cmd, '')
    def parse_cmd(self, cmd, data):
        #if cmd.find('DeviceSystem?'):
            dump = cPickle.dumps(self.server.DeviceSystem, -1)
            print 'dumped, len=', len(dump)
            self.request.send(dump)

if __name__ == "__main__":
    s = BackendServerBase("localhost", 9990)
    
